package com.yb.xczx.cloud.passport.controller;

import com.alibaba.fastjson2.JSONObject;
import com.yb.core.model.XczxResult;
import com.yb.xczx.cloud.passport.bean.Oauth2TokenResult;
import com.yb.xczx.cloud.passport.feign.client.AuthBasicClient;
import com.yb.xczx.cloud.passport.feign.client.AuthNoAuthClient;
import com.yb.xczx.cloud.passport.util.CacheUtil;
import feign.FeignException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Copyright (C), 2022-2023, 姚兵
 * Author: 32210
 * Date: 2023/5/19 15:43
 * FileName: LoginController
 * Description:
 */

//@Controller
@Slf4j
public class HelloController {

    @Autowired
    private AuthBasicClient authClient;

    @Autowired
    private AuthNoAuthClient authNoAuthClient;

    public HelloController(){
        CacheUtil.resultMap.put("xyz",null);
    }
    @GetMapping("login")
    @ResponseBody
    public XczxResult login(){

        return authClient.login("admin","admin");
    }

    @GetMapping("/login/key")
    @ResponseBody
    public XczxResult loginKey(){
        String state = UUID.randomUUID().toString();
        CacheUtil.resultMap.put(state,null );
        //TODO 返回随机字符串
        return XczxResult.success(state);
    }


    @GetMapping("/login/user")
    @ResponseBody
    public XczxResult loginUser(@RequestParam String state){
        //TODO 查询用户是否授权成功
        return XczxResult.success(CacheUtil.resultMap.get(state));
    }
//    @GetMapping("/oauth2/authorize")
//    public String authorize(String key, String accessToken, @RequestParam String state, HttpServletResponse response,@RequestHeader(HttpHeaders.HOST) String host){
//        String responseType="code";
//        String clientId="hello";
//        String scope="address%20phone%20openid%20profile%20custom%20email";
//        String redirectUri="http://gateway.51xuecheng.cn:63040/inner/passport/login/oauth2/code/hello";
////        response_type=code&client_id=login-client&scope=openid%20profile&redirect_uri=
//        String authorize = "";
//        try {
//            authorize = authNoAuthClient.authorize(responseType, clientId, scope, redirectUri,state);
//        }catch (FeignException e){
//            if (e.status()==302) {
//                String header = e.responseHeaders().get(HttpHeaders.LOCATION).stream().findFirst().get();
//                Matcher m = Pattern.compile("(?<schema>http|https)://(?<hostport>.*?)/(?<restpath>.*)").matcher(header);
//                if(m.find()){
//                    header=m.group(1)+"://"+host+"/inner/auth/";
//                    m.group(2);
//                    header+=m.group(3);
//                }
//                return "redirect:"+ header;
//            }
//            log.info("e:{}",e);
//        }
//        return authorize;
//    }

    @GetMapping("/redirect")
    public String redirect(@RequestHeader(HttpHeaders.HOST) String host){
        return "redirect:http://"+host;
    }

    @GetMapping("/login/oauth2/code/hello")
    public String loginCode(String key, String code, String state,HttpServletResponse response, HttpServletRequest httpServletRequest) throws IOException {
        String access_token="";
        log.info("code:{}",code);
//        POST http://localhost:9000/oauth2/token?code={{authCode}}&grant_type=authorization_code&redirect_uri=http://client:8080/login/oauth2/code/login-client&scope=openid%20profile
        String grant_type="authorization_code";
        String redirect_uri="http://gateway.51xuecheng.cn:63040/inner/passport/login/oauth2/code/hello";
        String scope="openid%20profile";
        String result=authClient.getToken(code,grant_type,redirect_uri,scope,"");

        CacheUtil.resultMap.put(state,JSONObject.parseObject(result, Oauth2TokenResult.class));
        response.setHeader("token", JSONObject.toJSONString(result));
        return "success";
//        return  "redirect:http://localhost:8080/success.html";
    }



}
